import { Image } from 'ant-design-vue';
import { h, render, ref, nextTick } from 'vue';

const usePreviewImg = () => {
  let container: HTMLElement | null = null;
  const visibleRef = ref(true);

  const cleanup = () => {
    if (container) {
      render(null, container); // 先卸载Vue组件
      document.body.removeChild(container);
      container = null;
    }
  };

  const show = (config: { list: string[]; current?: number }) => {
    // 清理前次实例
    cleanup();

    // 创建新容器
    container = document.createElement('div');
    document.body.appendChild(container);

    // 状态管理
    visibleRef.value = true;

    // 预览配置
    const previewConfig = {
      visible: visibleRef.value,
      current: config.current || 0,
      onVisibleChange: (vis: boolean) => {
        visibleRef.value = vis;
        if (!vis) {
          // 延迟清理保证过渡动画
          setTimeout(cleanup, 300);
        }
      },
    };

    // 动态更新预览配置
    const updatePreviewConfig = () => ({
      ...previewConfig,
      visible: visibleRef.value,
    });

    // 创建渲染函数
    const renderPreview = () => {
      return h(
        Image.PreviewGroup,
        { preview: updatePreviewConfig() },
        config.list.map((item, index) =>
          h(Image, {
            key: index,
            src: item,
            style: { display: 'none' },
          }),
        ),
      );
    };

    // 初始渲染
    render(renderPreview(), container);

    // 响应式更新
    const watchVisibility = () => {
      nextTick(() => {
        if (container) {
          render(renderPreview(), container);
        }
      });
    };

    watchVisibility();
  };

  return { show };
};

export default usePreviewImg;
